package com.example.appointment.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dou361.ijkplayer.bean.VideoijkBean;
import com.dou361.ijkplayer.listener.OnControlPanelVisibilityChangeListener;
import com.dou361.ijkplayer.listener.OnShowThumbnailListener;
import com.dou361.ijkplayer.widget.IjkVideoView;
import com.dou361.ijkplayer.widget.PlayStateParams;
import com.dou361.ijkplayer.widget.PlayerView;
import com.example.appointment.AppointmentApplication;
import com.example.appointment.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import java.util.ArrayList;
import java.util.Random;

import butterknife.Bind;

/**
 * 视频播放的界面
 */
public class VideoPlayActivity extends BaseActivity {
    private boolean iffilehas = false;//判断是否存在文件
    private PlayerView player;
    @Bind(R.id.video_view)
    IjkVideoView videoview;
    @Bind(R.id.app_video_download)
    ImageView downloadbtn;

    private ArrayList<VideoijkBean> list;
    private String title = "";


    private boolean showDanmaku;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**播放资源*/
//        iffilehas = true;
        if (!iffilehas) {
            list = new ArrayList<VideoijkBean>();

            String url1 = Environment.getExternalStorageDirectory().getPath() + "/zhongdou/" + "test.mp4";
            String url2 = "http://9890.vod.myqcloud.com/9890_9c1fa3e2aea011e59fc841df10c92278.f20.mp4";
            String url3 = "http://player.youku.com/player.php/sid/XMTY4OTgyMTM1Mg==/v.swf";
            VideoijkBean m1 = new VideoijkBean();
            m1.setStream("视频1");
            m1.setUrl(url1);
            VideoijkBean m2 = new VideoijkBean();
            m2.setStream("视频2");
            m2.setUrl(url2);
            VideoijkBean m3 = new VideoijkBean();
            m3.setStream("视频3");
            m3.setUrl(url2);
            list.add(m1);
            list.add(m2);
            list.add(m3);
/**播放器*/
            title = "什么";//这里的标题以后是要传过来的
            player = new PlayerView(this)
                    .setTitle(title)
                    .setScaleType(PlayStateParams.fitparent)
                    .hideMenu(true)
                    .forbidTouch(false)
                    .showThumbnail(new OnShowThumbnailListener() {
                        @Override
                        public void onShowThumbnail(ImageView ivThumbnail) {
                            /**加载前显示的缩略图*/

                            AppointmentApplication.getImageLoader().displayImage("http://pic2.nipic.com/20090413/406638_125424003_2.jpg", ivThumbnail,
                                    new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.qcloud_player_icon_audio_vol)
                                            .showImageOnFail(R.drawable.qcloud_player_icon_audio_vol)
                                           .build());
                        }
                    })
                    .setPlaySource(list)
                    .startPlay();
//        //旋转角度
//        PlayerView setPlayerRotation()
////旋转指定角度
//        PlayerView setPlayerRotation(int rotation)
//        //设置自动重连的模式或者重连时间，isAuto true 出错重连，false出错不重连，connectTime重连的时间
//        setAutoReConnect(boolean isAuto, int connectTime)
//        //设置是否禁止隐藏bar，true为一直显示，false为点击可以隐藏或显示
//        PlayerView setForbidHideControlPanl(boolean flag)
//        更多UI样式的设置
//
//        1.视频界面裁剪设置，可通过方法setScaleType(int type)去设置
//
//        （1）. PlayStateParams.fitParent:可能会剪裁,保持原视频的大小，显示在中心,当原视频的大小超过view的大小超过部分裁剪处理
//        （2）. PlayStateParams.fillParent:可能会剪裁,等比例放大视频，直到填满View为止,超过View的部分作裁剪处理
//        （3）. PlayStateParams.wrapcontent:将视频的内容完整居中显示，如果视频大于view,则按比例缩视频直到完全显示在view中
//        （4）. PlayStateParams.fitXY:不剪裁,非等比例拉伸画面填满整个View
//        （5）. PlayStateParams.f16_9:不剪裁,非等比例拉伸画面到16:9,并完全显示在View中
//        （6）. PlayStateParams.f4_3:不剪裁,非等比例拉伸画面到4:3,并完全显示在View中

//        2.播放器底部bar播放进度条样式定制 默认的进度样式是竖屏为上下样式，即进度条在播放时长的上面，横屏为左右样式，即进度条在播放时长的中间。样式定制主要是两个方法搭配使用toggleProcessDurationOrientation方法和setProcessDurationOrientation方法，横竖屏切换2中情况，和3种进度条样式
//
///**上下样式*/
//        PlayStateParams.PROCESS_PORTRAIT
///**左右样式*/
//        PlayStateParams.PROCESS_LANDSCAPE
///**中间两边样式*/
//        PlayStateParams.PROCESS_CENTER


////隐藏返回键，true隐藏，false为显示
//        PlayerView hideBack(boolean isHide)
////隐藏菜单键，true隐藏，false为显示
//        PlayerView hideMenu(boolean isHide)
////隐藏分辨率按钮，true隐藏，false为显示
//        PlayerView hideSteam(boolean isHide)
////隐藏旋转按钮，true隐藏，false为显示
//        PlayerView hideRotation(boolean isHide)
////隐藏全屏按钮，true隐藏，false为显示
//        PlayerView hideFullscreen(boolean isHide)
////隐藏中间播放按钮,ture为隐藏，false为不做隐藏处理，但不是显示
//        PlayerView hideCenterPlayer(boolean isHide)
////设置2/3/4/5G和WiFi网络类型提示 true为进行2/3/4/5G网络类型提示 false 不进行网络类型提示
//        PlayerView setNetWorkTypeTie(boolean isGNetWork)


//        butto.setText("點我");

//        Example in = new Example();
//        byte[] bytes = new byte[]{'q', 'w', 'w'};
//
//        in.setCover(bytes);
//        in.setName("sdsd");
//        in.setPrice(101);
//        in.save();
            //http://player.youku.com/embed/XOTU3NjQ1Mg==
//        Car car = new Car();
//        car.setPrice(123123);
//        car.setName("jjiii");
//        car.save();
            //1.简单的播放器实现
//        setContentView(R.layout.simple_player_view_player);
//        String url = "http://9890.vod.myqcloud.com/9890_9c1fa3e2aea011e59fc841df10c92278.f20.mp4";
//        PlayerView player = new PlayerView(this)
//                .setTitle("什么")
//                .setScaleType(PlayStateParams.fitparent)
//                .hideMenu(true)
//                .forbidTouch(false)
//                .showThumbnail(new OnShowThumbnailListener() {
//                    @Override
//                    public void onShowThumbnail(ImageView ivThumbnail) {
////                        Glide.with(mContext)
////                                .load("http://pic2.nipic.com/20090413/406638_125424003_2.jpg")
////                                .placeholder(R.color.cl_default)
////                                .error(R.color.cl_error)
////                                .into(ivThumbnail);
//                        AppointmentApplication.getImageLoader().displayImage("http://pic2.nipic.com/20090413/406638_125424003_2.jpg", ivThumbnail,
//                                new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.qcloud_player_icon_audio_vol)
//                                        .showImageOnFail(R.drawable.qcloud_player_icon_audio_vol).cacheInMemory(true).cacheOnDisk(true)
//                                        .imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build());
//                    }
//                })
//                .setPlaySource(url)
//                .startPlay();

//        PlayerView(Activity activity)
//
////生命周期方法回调
//        PlayerView onPause()
//        PlayerView onResume()
//        PlayerView onDestroy()
//        PlayerView onConfigurationChanged(final Configuration newConfig)
//        boolean onBackPressed()
////显示缩略图
//        PlayerView showThumbnail(OnShowThumbnailListener onShowThumbnailListener)
////设置播放信息监听回调
//        PlayerView setOnInfoListener(IMediaPlayer.OnInfoListener onInfoListener)
////设置播放器中的返回键监听
//        PlayerView setPlayerBackListener(OnPlayerBackListener listener)
////设置控制面板显示隐藏监听
//        PlayerView setOnControlPanelVisibilityChangListenter(OnControlPanelVisibilityChangeListener listener)
////百分比显示切换
//        PlayerView toggleAspectRatio()
////设置播放区域拉伸类型
//        PlayerView setScaleType(int showType)
////旋转角度
//        PlayerView setPlayerRotation()
////旋转指定角度
//        PlayerView setPlayerRotation(int rotation)
////设置播放地址包括视频清晰度列表对应地址列表
//        PlayerView setPlaySource(List<VideoijkBean> list)
////设置播放地址单个视频VideoijkBean
//        PlayerView setPlaySource(VideoijkBean videoijkBean)
////设置播放地址单个视频地址时带流名称
//        PlayerView setPlaySource(String stream, String url)
////设置播放地址单个视频地址时
//        PlayerView setPlaySource(String url)
////自动播放
//        PlayerView autoPlay(String path)
////开始播放
//        PlayerView startPlay()
////设置视频名称
//        PlayerView setTitle(String title)
////选择要播放的流
//        PlayerView switchStream(int index)
////暂停播放
//        PlayerView pausePlay()
////停止播放
//        PlayerView stopPlay()
////设置播放位置
//        PlayerView seekTo(int playtime)
////获取当前播放位置
//        int getCurrentPosition()
////获取视频播放总时长
//        long getDuration()
////设置2/3/4/5G和WiFi网络类型提示 true为进行2/3/4/5G网络类型提示 false 不进行网络类型提示
//        PlayerView setNetWorkTypeTie(boolean isGNetWork)
////是否仅仅为全屏
//        PlayerView setOnlyFullScreen(boolean isFull)
////设置是否禁止双击
//        PlayerView setForbidDoulbeUp(boolean flag)
////设置是否禁止隐藏bar
//        PlayerView setForbidHideControlPanl(boolean flag)
////当前播放的是否是直播
//        boolean isLive()
////是否禁止触摸
//        PlayerView forbidTouch(boolean forbidTouch)
////隐藏所有状态界面
//        PlayerView hideAllUI()
//        获取顶部控制barview
//        View getTopBarView()
////获取底部控制barview
//        View getBottonBarView()
////获取旋转view
//        ImageView getRationView()
////获取返回view
//        ImageView getBackView()
////获取菜单view
//        ImageView getMenuView()
////获取全屏按钮view
//        ImageView getFullScreenView()
////获取底部bar的播放view
//        ImageView getBarPlayerView()
////获取中间的播放view
//        ImageView getPlayerView()
////隐藏返回键，true隐藏，false为显示
//        PlayerView hideBack(boolean isHide)
////隐藏菜单键，true隐藏，false为显示
//        PlayerView hideMenu(boolean isHide)
////隐藏分辨率按钮，true隐藏，false为显示
//        PlayerView hideSteam(boolean isHide)
////隐藏旋转按钮，true隐藏，false为显示
//        PlayerView hideRotation(boolean isHide)
////隐藏全屏按钮，true隐藏，false为显示
//        PlayerView hideFullscreen(boolean isHide)
////隐藏中间播放按钮,ture为隐藏，false为不做隐藏处理，但不是显示
//        PlayerView hideCenterPlayer(boolean isHide)
////显示或隐藏操作面板
//        PlayerView operatorPanl()
////全屏切换
//        PlayerView toggleFullScreen()
////设置自动重连的模式或者重连时间，isAuto true 出错重连，false出错不重连，connectTime重连的时间
//        setAutoReConnect(boolean isAuto, int connectTime)
////进度条和时长显示的方向切换
//        PlayerView toggleProcessDurationOrientation()
////设置进度条和时长显示的方向，默认为上下显示，PlayStateParams.PROCESS_PORTRAIT为上下显示PlayStateParams.PROCESS_LANDSCAPE为左右显示PlayStateParams.PROCESS_CENTER为中间两边样式
//        setProcessDurationOrientation(int portrait)
////显示菜单设置
//        showMenu()
////获取界面方向
//        int getScreenOrientation()
////显示加载网速
//        PlayerView setShowSpeed(boolean isShow)
            /**
             * 12.ijkplayer封装的视频播放信息返回码监听，可以通过setOnInfoListener去监听
             *
             * /*
             * Do not change these values without updating their counterparts in native
             int MEDIA_INFO_UNKNOWN = 1;//未知信息
             int MEDIA_INFO_STARTED_AS_NEXT = 2;//播放下一条
             int MEDIA_INFO_VIDEO_RENDERING_START = 3;//视频开始整备中
             int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;//视频日志跟踪
             int MEDIA_INFO_BUFFERING_START = 701;//开始缓冲中
             int MEDIA_INFO_BUFFERING_END = 702;//缓冲结束
             int MEDIA_INFO_NETWORK_BANDWIDTH = 703;//网络带宽，网速方面
             int MEDIA_INFO_BAD_INTERLEAVING = 800;//
             int MEDIA_INFO_NOT_SEEKABLE = 801;//不可设置播放位置，直播方面
             int MEDIA_INFO_METADATA_UPDATE = 802;//
             int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
             int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;//不支持字幕
             int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;//字幕超时

             int MEDIA_INFO_VIDEO_INTERRUPT= -10000;//数据连接中断
             int MEDIA_INFO_VIDEO_ROTATION_CHANGED = 10001;//视频方向改变
             int MEDIA_INFO_AUDIO_RENDERING_START = 10002;//音频开始整备中

             int MEDIA_ERROR_UNKNOWN = 1;//未知错误
             int MEDIA_ERROR_SERVER_DIED = 100;//服务挂掉
             int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;//数据错误没有有效的回收
             int MEDIA_ERROR_IO = -1004;//IO错误
             int MEDIA_ERROR_MALFORMED = -1007;
             int MEDIA_ERROR_UNSUPPORTED = -1010;//数据不支持
             int MEDIA_ERROR_TIMED_OUT = -110;//数据超时
             *
             */
        } else {
////            videoview.set
////            player = new PlayerView(this)
////                    .setTitle("什么")
////                    .setScaleType(PlayStateParams.fitparent)
////                    .hideMenu(true)
////                    .forbidTouch(false)
////                    .showThumbnail(new OnShowThumbnailListener() {
////                        @Override
////                        public void onShowThumbnail(ImageView ivThumbnail) {
////                            /**加载前显示的缩略图*/
////
////                            AppointmentApplication.getImageLoader().displayImage("http://pic2.nipic.com/20090413/406638_125424003_2.jpg", ivThumbnail,
////                                    new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.qcloud_player_icon_audio_vol)
////                                            .showImageOnFail(R.drawable.qcloud_player_icon_audio_vol).cacheInMemory(true).cacheOnDisk(true)
////                                            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED).build());
////                        }
////                    });
//
//            try {
////                String url1 = "android.resource://" + getPackageName() + "/" + R.raw.test;
////                videoview.setDataSource(path);
////                videoview.setDisplay(surfaceHolder);
////
////                videoview.setAudioStreamType(AudioManager.STREAM_MUSIC);
////                videoview.setScreenOnWhilePlaying(true);
////                videoview.prepareAsync();
//                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//                setContentView(R.layout.activity_main);
//
//                // 初始化播放器
//                IjkMediaPlayer.loadLibrariesOnce(null);
//                IjkMediaPlayer.native_profileBegin("libijkplayer.so");
//
//
//                videoview.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.test));
//                videoview.seekTo(0);
//                videoview.start();
//                Log.d("sss", "onCreate: " + videoview);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }

        }

//    /**
//     * 點我
//     *
//     * @param view
//     */
//    @OnClick(R.id.buttonPanelsssss)
//    public void clickme(View view) {
//
//    }
//
//    @OnClick(R.id.buttonPanelssssssss)
//    public void click(View view) {
//
//        try {
//            List<Car> list = DataSupport.findAll(Car.class);
//            ((Button) view).setText(list.toString());
//        } catch (Exception e) {
//            Log.d("SQL", "cuole");
//        }
//    }

        player.setOnControlPanelVisibilityChangListenter(new OnControlPanelVisibilityChangeListener() {
            @Override
            public void change(boolean isShowing) {
                if (isShowing) {
                    downloadbtn.setVisibility(View.VISIBLE);
                } else {
                    downloadbtn.setVisibility(View.GONE);
                }
            }

        });

        downloadbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(VideoPlayActivity.this, "点击了下载的按钮", Toast.LENGTH_SHORT).show();


                for (VideoijkBean videoijkBean : list) {

                    if (videoijkBean.getStream().equals(((TextView) player.getBottonBarView().findViewById(R.id.app_video_stream)).getText().toString())) {
                        //如果是当前播放的視頻

                        Toast.makeText(VideoPlayActivity.this, "要下载的url是：" + videoijkBean.getUrl(), Toast.LENGTH_LONG).show();
                        VideoPlayActivity.this.startActivity(new Intent(VideoPlayActivity.this, DownloadActivity.class).putExtra("sourceurl", videoijkBean.getUrl()).putExtra("sourcename", title + "(" + videoijkBean.getStream() + ")"));
                    }
                }
            }
        });

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (player != null) {
            player.onPause();
        }
        /**demo的内容，恢复系统其它媒体的状态*/
        //MediaUtils.muteAudioFocus(mContext, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (player != null) {
            player.onResume();
        }
        /**demo的内容，暂停系统其它媒体的状态*/
//        MediaUtils.muteAudioFocus(mContext, false);
        /**demo的内容，激活设备常亮状态*/
        //if (wakeLock != null) {
        //    wakeLock.acquire();
        //}
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.onDestroy();
        }
        showDanmaku = false;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (player != null) {
            player.onConfigurationChanged(newConfig);
        }
    }

    @Override
    public void onBackPressed() {
        if (player != null && player.onBackPressed()) {
            return;
        }
        super.onBackPressed();
        /**demo的内容，恢复设备亮度状态*/
        //if (wakeLock != null) {
        //    wakeLock.release();
        //}
    }
    /**
     * sp转px的方法。
     */
    public int sp2px(float spValue) {
        final float fontScale = getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

}
